package com.demo.baidu;// 数据库表维护每个业务的最大ID和步长
// 示例表：id_generator (biz_tag VARCHAR, max_id BIGINT, step INT)

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SegmentIDGenerator {
    private final DataSource dataSource;
    private final String bizTag;
    private long maxId;
    private long currentId;
    private final int step;

    public SegmentIDGenerator(DataSource dataSource, String bizTag, int step) {
        this.dataSource = dataSource;
        this.bizTag = bizTag;
        this.step = step;
        this.maxId = 0;
        this.currentId = 0;
    }

    public synchronized long nextId() {
        if (currentId >= maxId) {
            fetchNextSegment();
        }
        return currentId++;
    }

    private void fetchNextSegment() {
        try (Connection conn = dataSource.getConnection()) {
            conn.setAutoCommit(false);
            PreparedStatement ps = conn.prepareStatement(
                "UPDATE id_generator SET max_id = max_id + ? WHERE biz_tag = ?");
            ps.setInt(1, step);
            ps.setString(2, bizTag);
            ps.executeUpdate();

            ps = conn.prepareStatement("SELECT max_id FROM id_generator WHERE biz_tag = ?");
            ps.setString(1, bizTag);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                maxId = rs.getLong("max_id");
                currentId = maxId - step;
            }
            conn.commit();
        } catch (SQLException e) {
            throw new RuntimeException("Failed to fetch next ID segment", e);
        }
    }
}
